package cn.lg.soar.core.annotations.constraints;

import cn.lg.soar.common.util.data.DataUtil;

import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 枚举验证，只允许枚举范围内的值
 * @author luguoxiang
 * @date 2021/9/28
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.TYPE_USE})
@Retention(value = RetentionPolicy.RUNTIME)
@Constraint(validatedBy= Distinct.Validator.class)
public @interface Distinct {

    String message() default "数据重复";

    boolean required() default true;

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    /**
     * 校验器
     */
    class Validator implements ConstraintValidator<Distinct, Object> {

        private boolean required;

        @Override
        public void initialize(Distinct ca) {
            this.required = ca.required();
        }

        @Override
        public boolean isValid(Object s, ConstraintValidatorContext constraintValidatorContext) {
            if (s == null) {
                return !this.required;
            }
            if (s instanceof Set) {
                return true;
            }
            if (s instanceof Collection) {
                Collection collection = (Collection) s;
                if (collection.size() <= 1) {
                    return true;
                }
                Set set = new HashSet<>();
                set.addAll(collection);
                return set.size() == collection.size();
            }
            if (s.getClass().isArray()) {
                List<Object> list = DataUtil.arrayToList(s);
                return list.size() == list.stream().distinct().toArray().length;
            }
            return true;
        }

    }

}
